// utils/api.js
/**
 * 针对你的接口 http://xzwin80.frp.smallblog.cn 的 fetch 封装
 */
class ApiClient {
    constructor() {
        this.baseURL = 'http://xzwin80.frp.smallblog.cn';
        this.defaultHeaders = {
            'Content-Type': 'application/json'
        };
        this.timeout = 10000; // 10秒超时
    }

    // 从 chrome.storage 或 localStorage 获取 token
    async getToken() {
        return new Promise((resolve) => {
            if (typeof chrome !== 'undefined' && chrome.storage) {
                chrome.storage.local.get(['authToken'], (result) => {
                    resolve(result.authToken || null);
                });
            } else {
                resolve(localStorage.getItem('authToken'));
            }
        });
    }

    // 核心请求方法
    async request(url, options = {}) {
        const fullURL = this.baseURL + url;
        const controller = new AbortController();
        const id = setTimeout(() => controller.abort(), options.timeout || this.timeout);

        // 合并 headers
        const token = await this.getToken();
        const headers = { ...this.defaultHeaders };

        if (token && !options.headers?.['isToken'] === 'false') {
            // 只有在需要 token 时才添加（isToken !== false）
            headers['Authorization'] = `Bearer ${token}`;
        }

        // 合并用户传入的 headers
        if (options.headers) {
            Object.assign(headers, options.headers);
        }

        const config = {
            method: 'GET',
            headers,
            ...options,
            signal: controller.signal
        };

        // 自动序列化 JSON body
        if (config.body && typeof config.body === 'object' && !(config.body instanceof FormData)) {
            config.body = JSON.stringify(config.body);
        }

        try {
            const response = await fetch(fullURL, config);
            clearTimeout(id);

            if (!response.ok) {
                let errorData;
                try {
                    errorData = await response.json();
                } catch {
                    errorData = { message: `HTTP ${response.status}` };
                }
                throw new Error(errorData.message || `请求失败: ${response.status}`);
            }

            // 解析响应
            const contentType = response.headers.get('content-type');
            const data = contentType?.includes('application/json')
                ? await response.json()
                : await response.text();

            return { success: true, data, status: response.status };

        } catch (error) {
            clearTimeout(id);

            if (error.name === 'AbortError') {
                return { success: false, error: '请求超时，请检查网络或服务是否正常' };
            }

            if (error.message.includes('Failed to fetch')) {
                return { success: false, error: '无法连接到服务，请确认后端已启动且地址正确' };
            }

            return { success: false, error: error.message };
        }
    }

    // 便捷方法（支持传入 headers）
    get(url, params = {}, headers = {}) {
        const searchParams = new URLSearchParams(params);
        const queryString = searchParams.toString();
        const urlWithParams = queryString ? `${url}?${queryString}` : url;
        return this.request(urlWithParams, { method: 'GET', headers });
    }

    post(url, body = {}, headers = {}) {
        return this.request(url, { method: 'POST', body, headers });
    }

    put(url, body = {}, headers = {}) {
        return this.request(url, { method: 'PUT', body, headers });
    }

    delete(url, headers = {}) {
        return this.request(url, { method: 'DELETE', headers });
    }
}

// ==================== 创建实例 ====================
const api = new ApiClient();

// ==================== 接口封装 ====================

/**
 * 登录方法 - 使用 api.post()，复用统一逻辑
 * @param {string} username
 * @param {string} password
 * @param {string} code
 * @param {string} uuid
 * @returns {Promise}
 */
export async function login(username, password, code, uuid) {
    const res = await api.post('/login', {
        username,
        password,
        code,
        uuid
    }, {
        // 特殊 header：登录时不检查 token
        isToken: 'false',
        repeatSubmit: 'false'
    });

    // 登录成功后保存 token
    if (res.success && (res.data.code === 200 || res.data.code === 0)) {
        const token = res.data.token;
        if (token) {
            await new Promise((resolve) => {
                if (typeof chrome !== 'undefined' && chrome.storage) {
                    chrome.storage.local.set({
                        authToken: token,
                        isLoggedIn: true,
                        loginTime: Date.now()
                    }, resolve);
                } else {
                    localStorage.setItem('authToken', token);
                    localStorage.setItem('isLoggedIn', 'true');
                    resolve();
                }
            });
        }
        return { success: true, data: res.data };
    }

    return res; 
}

// 测试连通性
export async function testConnection() {
    const res = await api.get('/ping'); // 假设后端有此接口
    if (res.success) {
        console.log('✅ 服务连接正常:', res.data);
    } else {
        console.error('❌ 服务不可达:', res.error);
    }
    return res;
}

// 导出
export default api;